﻿using System;
using System.Threading;

namespace AlarmClock
{
    public class AlarmClock
    {
        public event EventHandler Tick;

        protected virtual void OnTick()
        {
            Tick?.Invoke(this, EventArgs.Empty);
        }

        public event EventHandler Alarm;

        protected virtual void OnAlarm()//触发Alarm
        {
            Alarm?.Invoke(this, EventArgs.Empty);
        }


        public void Start(int seconds)
        {
            Thread thread = new Thread(() =>
            {
                while (true)
                {
                    Thread.Sleep(seconds * 1000);
                    OnTick();
                }
            });
            thread.IsBackground = true;
            thread.Start();
        }

        public void SetAlarm(int hours, int minutes, int seconds)
        {
            //延时触发 Alarm 事件
            Thread thread = new Thread(() =>
            {
                Thread.Sleep(1000*(3600*hours+60*minutes+seconds));
                OnAlarm();
            });
            thread.IsBackground = true;
            thread.Start();
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            AlarmClock alarmClock = new AlarmClock();

            // 订阅事件
            alarmClock.Tick += AlarmClock_Tick;
            alarmClock.Alarm += AlarmClock_Alarm;

            // 设置响铃时间
            // 设置响铃时间
            Console.WriteLine("请输入闹钟的响铃时间（时 分 秒，以空格分隔）：");
            string[] input = Console.ReadLine().Split(' ');
            if (input.Length == 3 && int.TryParse(input[0], out int hours) && int.TryParse(input[1], out int minutes) && int.TryParse(input[2], out int seconds))
            {
                // 启动闹钟
                alarmClock.Start(1); // 每秒触发一次 Tick 事件
                alarmClock.SetAlarm(hours, minutes, seconds); // 设置响铃时间
                Console.WriteLine($"闹钟已设置为 {hours} 时 {minutes} 分 {seconds} 秒后响铃");
            }
            else
            {
                Console.WriteLine("输入格式不正确，无法设置闹钟时间。");
            }

            Console.ReadKey();
        }

        static void AlarmClock_Tick(object sender, EventArgs e)
        {
            Console.WriteLine("Tick...");
        }
        static void AlarmClock_Alarm(object sender, EventArgs e)
        {
            Console.WriteLine("Alarm! Wake up!");
        }
    }
}


